package com.lw.extraceim.ui.activity.tp;

import androidx.annotation.Nullable;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lw.extraceim.R;
import com.lw.extraceim.loader.PackageLoader;
import com.lw.extraceim.model.CustomerInfo;
import com.lw.extraceim.model.ExpressSheet;
import com.lw.extraceim.model.TransPackage;
import com.lw.extraceim.net.HttpResponseParam;
import com.lw.extraceim.net.ResponseCode;
import com.lw.extraceim.net.callback.HttpResponseParamCallback;
import com.lw.extraceim.ui.activity.base.BaseActivity;
import com.lw.extraceim.ui.activity.es.ExpressSheetInfoActivity;
import com.lw.extraceim.ui.adapter.ExpressSheetAdapter;
import com.lw.extraceim.util.JsonUtils;
import com.lw.extraceim.util.TextUtil;
import com.lw.extraceim.view.ExtraceToolbar;
import com.lw.extraceim.zxing.ExtraceCaptureActivity;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * @Author : liwei
 * @Email : 1759840027@qq.com
 * @Description : 包裹信息的编辑界面
 * @Date : 2019/4/20 14:28
 */
public class PackageEditActivity extends BaseActivity {

    private static final String TAG = "PackageEditActivity";

    private LinearLayout mLlPackagePageInfo;//包裹信息编写的布局
    private EditText mEdPackageNumber;//新包裹的编号，通过扫码获得
    private EditText mEdPackageFrom;//新包裹的出发网点
    private EditText mEdPackageTo;//新包裹的目的网点
    private Button mButtonSavePackage;//点击保存该包裹的按钮

    private TransPackage transPackage;//当前编辑的包裹

    private ExtraceToolbar mToolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_package_edit);
        mToolbar = findViewById(R.id.toolbar);
        initToolBar();

        //包裹信息编写布局初始化
        mLlPackagePageInfo = findViewById(R.id.ll_package_page_info);
        mEdPackageNumber = findViewById(R.id.ed_package_number);
        mEdPackageFrom = findViewById(R.id.ed_package_from);
        mEdPackageTo = findViewById(R.id.ed_package_to);
        mButtonSavePackage = findViewById(R.id.button_save_package);
    }

    /**
     * 初始化toolBar
     */
    protected void initToolBar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mToolbar.setBackButtonOnClickListerner(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PackageEditActivity.this.finish();
            }
        });
        mToolbar.setButtonOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(transPackage.isSaved()) {
                    AddEsActivity.actionStart(PackageEditActivity.this, transPackage);
                }else{
                    toast("请先保存包裹信息");
                }
            }
        });
    }

    @Override
    public void initData() {
        transPackage = (TransPackage) getIntent().getSerializableExtra("package");
        loadTransPackage();
        refreshUI();
    }

    @Override
    public void refreshUI() {
        if (transPackage != null) {
            mEdPackageNumber.setText(transPackage.getId() != null ? transPackage.getId() : "");
            mEdPackageFrom.setText(transPackage.getId() != null ? transPackage.getSourceNode() : "");
            mEdPackageTo.setText(transPackage.getTargetNode() != null ? transPackage.getTargetNode() : "");
        }
    }

    @Override
    public void initEvent() {
        mButtonSavePackage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveTransPackage();
            }
        });
    }


    private HttpResponseParamCallback packageCallback = new HttpResponseParamCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            alert("网络错误" + e.getMessage());
        }

        @Override
        public void onResponse(HttpResponseParam response, int id) {
            Log.d(TAG, "onResponse: "  + response.reseponseJson);
            if(response.code.getCode() == ResponseCode.SUCESS){
                try {
                    transPackage = JsonUtils.fromJson(response.reseponseJson.getJSONObject("package").toString(),new TypeToken<TransPackage>(){});
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (transPackage!= null){
                    toast("保存成功");
                    transPackage.onLoad();
                    refreshUI();//刷新界面
                }else{
                    toast("保存失败");
                }
            }else{
                alert(response.code.getMessage());
            }
        }
    };

    public void loadTransPackage() {
        PackageLoader loader = new PackageLoader(this);
        if(transPackage != null){
//            loader.get(transPackage.getID(),packageCallback);
        }

    }

    public void saveTransPackage() {
        //保存包裹信息 根据返回信息更新包裹信息
        //要修改包裹的Save属性

        //加载包裹信息和包裹中的快件信息
        PackageLoader loader = new PackageLoader(this);
        if (checkInput()) {
            if (transPackage.isSaved()) {
                loader.update(transPackage, packageCallback);
            } else {
                loader.save(transPackage,application.getUserInfo().getuId(),packageCallback);
            }
        }
    }

    public boolean checkInput() {
        transPackage = (transPackage == null ? new TransPackage() : transPackage);
        transPackage.setId(mEdPackageNumber.getText().toString().trim());
        if(TextUtil.isNull(transPackage.getId())){
            toast("快递单号不能为空");
            return false;
        }
        transPackage.setSourceNode(mEdPackageFrom.getText().toString().trim());
        if (TextUtil.isNull(transPackage.getSourceNode())){
            toast("发出节点不能为空");
            return false;
        }
        transPackage.setTargetNode(mEdPackageTo.getText().toString().trim());
        if(TextUtil.isNull(transPackage.getTargetNode())){
            toast("目的节点不能为空");
            return false;
        }
        return true;
    }

    public ExpressSheet loadExpressSheet(String expressSheetId) {
        ExpressSheet expressSheet = new ExpressSheet();
        expressSheet.setId(expressSheetId);
        expressSheet.setStatus(0);
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setName("李伟");
        customerInfo.setRegionString("河南省 郑州市 高新区");
        customerInfo.setAddress("科学大道100号");
        customerInfo.setPostCode(454545);
        customerInfo.setTelCode("17803878845");
        customerInfo.setId(10);
        expressSheet.setSender(customerInfo);
        expressSheet.setRecever(customerInfo);
        return expressSheet;
    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ExtraceCaptureActivity.SCAN_SEARCH: {
                    IntentResult scanResult = IntentIntegrator.parseActivityResult(IntentIntegrator.REQUEST_CODE, resultCode, data);
                    if (scanResult != null) {
                        String expressSheetId = scanResult.getContents();
                    } else {
                        Toast.makeText(this, "扫描错误", Toast.LENGTH_LONG).show();
                    }
                    break;
                }
            }
        }

    }

//    /**
//     * 结束activity 并返回值
//     */
//    public void finshWithResponseResult() {
//        Intent intent = new Intent();
//        Bundle bundle = new Bundle();
//        if (transPackage != null) {
//            bundle.putSerializable("package", transPackage);
//            intent.putExtras(bundle);
//            //设置返回数据
//            this.setResult(RESULT_OK, intent);//编辑成功
//        } else {
//            this.setResult(RESULT_CANCELED); //编辑失败
//        }
//        //关闭Activity
//        this.finish();
//    }

    @Override
    public void onBackPressed() {
        this.finish();
    }


    /**
     * 启动PackageEditActivity 并要求返回结果
     *
     * @param context
     * @param requestCode
     * @param transPackage
     */
    public static void actionStart(Activity context, int requestCode, TransPackage transPackage) {
        Intent intent = new Intent(context, PackageEditActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("package", transPackage);
        intent.putExtras(bundle);
        context.startActivityForResult(intent, requestCode);
//        context.startActivity(intent);
    }

    /**
     * 启动PackageEditActivity
     *
     * @param context
     * @param transPackage
     */
    public static void actionStart(Activity context, TransPackage transPackage) {
        Intent intent = new Intent(context, PackageEditActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("package", transPackage);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }
}
